<template>
	<a-time-range-picker
		v-if="type === 'timePicker'"
		v-model:value="curValue"
		:inputReadOnly="readOnly"
        :disabled="disabled || readOnly"
		:format="format"
		:valueFormat="valueFormat"
		:placeholder="placeholder"
		:size="size"
        @blur="onBlur"
        @focus="onFocus"
        @change="onChange"
	/>
	<a-range-picker
		v-else
		v-model:value="curValue"
		:inputReadOnly="readOnly"
        :disabled="disabled || readOnly"
		:format="format"
		:valueFormat="valueFormat"
		:placeholder="placeholder"
		:show-time="showTime"
		:size="size"
        @blur="onBlur"
        @focus="onFocus"
        @change="onChange"
	/>
</template>
<script setup lang="ts">
import { IEvent } from '@/core';
import { computed, Ref } from 'vue';
import dayjs, { Dayjs } from 'dayjs';
import { dateRangePickerProps } from './date-range-picker';
import weekday from "dayjs/plugin/weekday";
import localeData from "dayjs/plugin/localeData";
import { useEditorTypeParams } from '@/hooks/use-editor';

dayjs.extend(weekday);
dayjs.extend(localeData);

interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const props = defineProps(dateRangePickerProps);
const emit = defineEmits<EditorEmit>();
// 类型校验
const { validateConfig } = useEditorTypeParams();
validateConfig();
const curValue: Ref<Dayjs[]> = computed(() => {
	if (props.value) {
		return props.value.split(props.valueSeparator).map((date: string) => {
            return dayjs(date);
        });
	} else {
		return [];
	}
});
const placeholder: Ref<string[]> = computed(() => {
    const startPlaceholder: string = props.startPlaceholder || App.ts('common.datepicker.placeholder');
    const endPlaceholder: string = props.endPlaceholder || App.ts('common.datepicker.placeholder');
    return [startPlaceholder, endPlaceholder]
})
const onChange = (date: any, dateString: string[]) => {
    const value = date ? dateString.join(props.valueSeparator) : null;
    emit('component-action', {
        name: `${props.name}`,
        action: 'valueChange',
        data: value,
    });
    if (props.valueItemNames) {
        props.valueItemNames.split(',').forEach((valueItemName: string, index: number) => {
            emit('component-action', {
                name: valueItemName,
                action: 'valueChange',
                data: dateString[index],
            });
        })
    }
};

const onBlur = () => {
	emit('component-action', {
		name: `${props.name}`,
		action: 'editorBlur',
		data: props.value,
	});
};
const onFocus = () => {
	emit('component-action', {
		name: `${props.name}`,
		action: 'editorFocus',
		data: props.value,
	});
};
</script>
